<script lang="ts" setup>
import { ref } from "vue";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { UploadChangeParam, UploadProps } from "ant-design-vue";
import { uploadPictureUsingPost } from "@/api/pictureController.ts";

function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

const loading = ref<boolean>(false);
const imageUrl = ref<string>("");

const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};

const beforeUpload = (file: UploadProps["fileList"][number]) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("不支持使用这种图片格式，请使用jpg或png格式的图片");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("不能上传超过2M的图片");
  }
  return isJpgOrPng && isLt2M;
};

const handleUpload = async ({ file }) => {
  loading.value = true;
  const params = props.picture ? { id: props.picture.id } : {};
  const res = await uploadPictureUsingPost(params, {}, file);
  if (res.code === 0 && res.data) {
    message.success("图片上传成功");
    props.onSuccess(res.data);
  } else {
    message.error("图片上传失败，" + res.message);
  }
  loading.value = false;
};

interface Props {
  picture?: API.PictureVO;
  onSuccess?: (newPicture: API.PictureVO) => void;
}

const props = defineProps<Props>();
</script>

<template>
  <div class="picture-upload">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :custom-request="handleUpload"
      :before-upload="beforeUpload"
    >
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传图片</div>
      </div>
    </a-upload>
  </div>
</template>

<style scoped>
.picture-upload {
  :deep(.ant-upload) {
    width: 100% !important;
    height: 100% !important;
    min-width: 152px;
    min-height: 152px;
  }

  img {
    max-width: 100%;
    max-height: 320px;
  }
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
